package com.itany.shop.service.impl;

import com.itany.shop.dao.ItemDao;
import com.itany.shop.dao.OrderDao;
import com.itany.shop.entity.Item;
import com.itany.shop.entity.Order;
import com.itany.shop.entity.User;
import com.itany.shop.exception.UserNotLoginException;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.OrderService;
import com.itany.shop.util.ParameterUtil;
import com.itany.shop.vo.Cart;

import java.util.List;

/**
 * @Author:石小俊
 * @Date:2022/11/16 17:03
 * @Version:1.0-SNAPSHOT
 * @Description:
 */
public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao = (OrderDao) ObjectFactory.getObject("orderDao");
    private ItemDao itemDao = (ItemDao) ObjectFactory.getObject("itemDao");

    @Override
    public String createOrder(Cart cart, User user) throws UserNotLoginException {
        if(null == cart || null == user){
            throw new UserNotLoginException("请先登录");
        }

        // 由于保存订单明细时需要用到订单的编号
        // 因此,必须先保存订单,将返回的主键交给明细

        // 创建订单对象
        Order order = new Order();
        order.setUser(user);
        order.setPrice(cart.getPrice());
        order.setNo(ParameterUtil.getNo());
        Integer id = orderDao.insertReturnPrimaryKey(order);
        // 将返回的主键设置给order对象
        order.setId(id);
        // 遍历购物车中所有的明细信息
        List<Item> items = cart.getItems();
        for(Item item : items){
            // 每条明细均属于当前保存的订单
            item.setOrder(order);
            // 每遍历一条数据,保存一条数据
            itemDao.insertItem(item);
        }

        return order.getNo();
    }
}
